#!/usr/bin/python
# -*- coding: latin-1 -*-
#-------------------------------------------------------------------------------
# Name:        utils.py
# Purpose:     BrailleMusicML utility functions
#
# Author:      Enrico
#
# Created:     23.06.2008
# Copyright:   (c) Veia Progetti s.r.l. 2008
#-------------------------------------------------------------------------------

def get_element_at_pos(parent, pos):
    """ return a list of tuple corresponding to the element and it's children
        at a given position. Each tuple entry is composed by
        object, start_pos, end_pos
    """
    ret = []
    if not hasattr(parent, '_is_container') or not parent._is_container:
        raise ValueError('%s is not a container' % parent)
    if not hasattr(parent, '_doc_element') or not parent._doc_element:
        raise ValueError('%s is not a doc element' % parent)
    if pos < 0:
        pos = parent.get_textlen() + pos
    start_pos = 0
    empty = True  #parent has no children
    while True:
        down = False  #go down one level
        for item in parent.iter_textelements():
            empty = False
            end_pos = start_pos + item.get_textlen()
            if pos < end_pos:
                ret.append((item, start_pos, end_pos))
                if hasattrs(item, '_is_container') and item._is_container:
                    parent = item
                    down = True
                break
            else:
                start_pos = end_pos
        if not down:
            break
    return ret if not empty else None
